package com.mitu.nio.gruopchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

public class GroupChatServer {
    //定义相关的属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    //构造器 完成初始化
    public GroupChatServer() {
        try {
            //得到选择器
            selector = Selector.open();
            //初始化ServeSocketChannel
            listenChannel = ServerSocketChannel.open();
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress("127.0.0.1", PORT));
            //设置非阻塞
            listenChannel.configureBlocking(false);
            //将listenChannel注册到selector上
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);   //新的连接事件
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //完成监听的代码
    public void listen() {
        try {
            //先阻塞2s然后开始循环监听
            while (true) {
                //获取到有哪些事件发生
                int count = selector.select();
                if (count > 0) {
                    //说明有相关的事件要处理
                    //遍历得到SelectionKey集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        //取出selectedKey
                        SelectionKey key = iterator.next();
                        //判断该key是什么事件
                        if (key.isAcceptable()) {
                            //新的连接事件,获取新的SocketChannel
                            SocketChannel newSocketChannel = listenChannel.accept();
                            //设置为非阻塞
                            newSocketChannel.configureBlocking(false);
                            //注册到选择器上,并绑定read事件(有读的事件就会触发)
                            newSocketChannel.register(selector, SelectionKey.OP_READ);
                            System.out.println(newSocketChannel.getRemoteAddress() + "上线了...");
                        }
                        //读事件(通道发生了Read事件,通道是可读状态)
                        if (key.isReadable()) {
                            //处理读...
                            readData(key);
                        }
                        //将当前的key进行删除，防止重复处理
                        iterator.remove();
                    }
                } else {
                    System.out.println("等待...");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    //读取客户端消息
    private void readData(SelectionKey key) {
        //定义SocketChannel
        SocketChannel channel = null;
        try {
            //取到关联的Channel
            channel = (SocketChannel) key.channel();
            //创建ByteBuffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            //根据count的值做处理
            if (count > 0) {
                //读取到了数据,把缓冲区的数据转为字符串
                String message = new String(buffer.array());
                //输出该消息
                System.out.println("from 客户端:" + message);
                //向其它的客户端转发消息(去掉自己)
                sendInfoToOntherClient(message, channel);
            }

        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + "离线了...");
                //取消注册和关闭这个出问题的通道
                key.cancel();
                channel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    //转发消息给选择器上的其他通道
    private void sendInfoToOntherClient(String message, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中...");
        //遍历所有的注册到Selector上的SocketChannel，并排除自己
        for (SelectionKey key : selector.keys()) {
            //通过key取出对应的通道
            Channel targetChannel = key.channel();
            //排除自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                //转型
                SocketChannel dest = (SocketChannel) targetChannel;
                //将信息存储到Buffer中
                ByteBuffer buffer = ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8));
                //将buffer中的数据写入到通道
                dest.write(buffer);
            }
        }
    }


    public static void main(String[] args) {
        GroupChatServer server = new GroupChatServer();
        server.listen();

    }
}
